import {
    addCategoryApi,
    delCategoryApi,
    editCategoryApi
} from '@/api/cms/category/category'
import {
    CategoryModel,
    AddCategoryModel,
    CategoryParam
} from '@/api/cms/category/CategoryModel'
import useInstance from '@/hooks/useInstance'
import { Result, StatusCode } from '@/http/request'
import { EditType } from '@/types/BaseEnum'
import { reactive, ref } from 'vue'

export default function useCategory(getCategoryTable: any) {
    const { global } = useInstance()

    const addEditRef = ref<{
        show: (type: string, row?: CategoryModel) => void
    }>()

    const addModel = reactive<CategoryModel>({
        id: '',
        editType: '',
        parent_id: '',
        name: '',
        sort: 0,
        status: '1'
    })

    // 新增
    const addBtn = (parentId: string) => {
        addModel.parent_id = parentId
        addEditRef.value?.show(EditType.ADD, addModel)
    }

    // 编辑
    const editBtn = async (row: CategoryModel) => {
        row.status = String(row.status)
        addEditRef.value?.show(EditType.EDIT, row)
    }

    // 删除
    const delBtn = async (id: number) => {
        const confirm = await global.$eleConfirm('确定删除该数据吗？')
        if (confirm) {
            // 执行删除操作
            let res = await delCategoryApi(
                reactive<CategoryParam>({
                    id: id
                })
            )
            if (res && res.code == StatusCode.Success) {
                // 刷新列表
                getCategoryTable()
                // 信息提示
                global.$message({ message: res.msg, type: 'success' })
            }
        }
    }

    // 保存
    const save = async (param: CategoryModel) => {
        const menuParam = reactive<AddCategoryModel>({
            id: param.id,
            editType: param.editType,
            parent_id: parseInt(param.parent_id),
            name: param.name,
            sort: param.sort,
            status: parseInt(param.status)
        })
        console.log('保存', menuParam)
        let res: Result
        if (param.editType == EditType.ADD) {
            res = await addCategoryApi(menuParam)
        } else {
            res = await editCategoryApi(menuParam)
        }
        if (res && res.code == StatusCode.Success) {
            // 刷新列表
            getCategoryTable()
            // 信息提示
            global.$message({ message: res.msg, type: 'success' })
        }
    }
    return {
        addBtn,
        editBtn,
        delBtn,
        save,
        addEditRef
    }
}
